#include "tcpClient.hpp"
#include "tcpServer.hpp"
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>

using namespace std;

namespace server {
boost::asio::io_context io_context_inst;
void io_context_run() { io_context_inst.run(); }
class taskServer : public tcpServer {
public:
  taskServer(short port) : tcpServer(io_context_inst, port) {}
};
void save_to_file(csn::TaskPackage_ptr pkg, std::string filename) {
  std::cout << "write to " << filename << std::endl;
  std::fstream file(filename, std::ios::binary | std::ios::out);
  file.write((char *)pkg->getPayload(), pkg->getPayloadSize());
  file.close();
}
} // namespace server

int main(int argc, char *argv[]) {
  try {
    if (argc != 2) {
      std::cerr << "Usage: "
                << "Server.exe"
                << " <port>\n";
      return 1;
    }
    server::taskServer s(std::atoi(argv[1]));
    std::thread([&]() { server::io_context_run(); }).detach();
    csn::TaskPackage_ptr pkg;

    std::thread([&]() {
      while (1) {
        if (s.pop_pkg(pkg)) {
          pkg->show_content();
          // stringstream ss;
          // ss << pkg->getExtMsg();
          // server::save_to_file(pkg, ss.str());
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
      }
    }).detach();

    std::string line;
    while (1) {
      std::cin >> line;
      auto pkg = std::make_shared<csn::TaskPackage>(line);
      tcpSession_ptr session =std::dynamic_pointer_cast<tcpSession>(s.get_session_by_id(0));
      session->write(pkg);
    }
  } catch (std::exception &e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}
